const jwt = require("jsonwebtoken")

module.exports = () => {
    return async (ctx, next) => {
        const whitePath = ["/api/login"];
        if (whitePath.includes(ctx.path)) {
            await next()
        } else {
            let token = ctx.get("token")
            try {
                jwt.verify(token, "123456");
                await next()
            } catch (error) {
                if(error.name === "TokenExpireError" || error.name === "JsonWebTokenError"){
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:error.message
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:error.message
                    }
                }
            }
        }
    }
}